##
rm(list=ls())
gc()

library(ggplot2)
library(scales)
library(data.table)
library(stringr)
library(dplyr)
library(tibble)
library(glue)
library(scales)
library(tidyr)
library(cowplot)
### Figure 3 - SEGREGATION CHANGES DISTRIBUTION

# Here, we want to output graphics that plot the distribution of year over year changes in segregation for each linked analysis dataset.






# Load files 
data = rbindlist(lapply(c('panel-analysis-2008-2012.csv.gz',
                          'panel-analysis-2012-2016.csv.gz',
                          'panel-analysis-2016-2020.csv.gz'), FUN = function(x){
  d=fread(x, select = c('DemSpExpDiff_nohh','RepSpExpDiff_nohh'))[,Years:=str_replace(str_replace(x, '.csv.gz', ''),'panel-analysis-','')]
                          }))



## Make Plots 

holder1 = data[,c('DemSpExpDiff_nohh','Years')]
holder1[,Exposure:=DemSpExpDiff_nohh][,Exposure.Type:='Exposure\nto Democrats']
holder1= holder1[,c('Exposure','Exposure.Type', 'Years')]

holder2 = data[,c('RepSpExpDiff_nohh','Years')]
holder2[,Exposure:=RepSpExpDiff_nohh][,Exposure.Type:='Exposure\nto Republicans']
holder2= holder2[,c('Exposure','Exposure.Type', 'Years')]

holder = rbind(holder1,holder2)

rm(holder1,holder2)
gc()

colors = c(`Exposure\nto Democrats` = "#377EB8",`Exposure\nto Republicans` = "#E41A1C")



g=  ggplot(data=holder, aes(x=Exposure,color=Exposure.Type, linetype=Years))+
  geom_density()+
  theme_bw()+
  facet_grid(rows = vars(Exposure.Type))+
  scale_linetype_manual(values=c('dotted','dashed', 'solid'))+
  theme(legend.position='bottom', legend.title=element_blank(), text=element_text(size=18))+
  scale_color_manual(values=colors) +
  xlim(-.5,.5)+
  theme(text=element_text(family='serif', size = 24))+
  xlab('')+
  ylab('Density')+
  guides(color='none')




names(data) = c( 'Exposure\nto Democrats', 'Exposure\nto Republicans', 'Years')
###


# get values for central tendencies
d = holder[,list(Mean=mean(Exposure,na.rm=T), Median=median(Exposure,na.rm=T),SD=sd(Exposure,na.rm=T)),by=c('Years','Exposure.Type')]%>%
  as_tibble()%>%
  pivot_longer(Mean:SD)

d = d %>% mutate(Exposure.Type=factor(Exposure.Type, levels = c('Exposure\nto Republicans','Exposure\nto Democrats')))

# theme for central tendency part of figure
theme_jake_tile2 <- function(base_size = 10, base_family = "serif",
                             base_line_size = base_size / 22,
                             base_rect_size = base_size / 22) {
  # Starts with theme_bw and remove most parts
  theme_bw(
    base_size = base_size,
    base_family = base_family,
    base_line_size = base_line_size,
    base_rect_size = base_rect_size
  ) %+replace%
    theme(
      plot.title = element_text(size = 15),
      panel.grid.major = element_blank(), 
      panel.grid.minor = element_blank(),
      axis.ticks      = element_blank(),
      legend.background = element_blank(),
      legend.key        = element_blank(),
      panel.background  = element_blank(),
      panel.border      = element_blank(),
      strip.background  = element_blank(),
      plot.background   = element_blank(),
      legend.position   = 'none',
      # axis.title.x=element_blank()
      
      complete = TRUE
    )
}
d$y=1

d$value=round(d$value, digits = 2)
d$value=ifelse(d$value==0,0,d$value)
t=ggplot(d,aes(y=Exposure.Type, x = name,fill=Exposure.Type,  label = sprintf("%0.2f", value)))+
  geom_tile(alpha=.75)+
  scale_fill_manual(values=colors)+
  geom_text( size = 5, alpha =1, color='black') +
  scale_x_discrete(position = "top") +
  scale_y_discrete(position = "right") +
  geom_vline(xintercept = 1:8 - 0.5, colour = "white", size = 1) +
  geom_hline(yintercept = 1:8 - 0.5, colour = "white", size = 1) +
  ylab("") +  
  xlab('') +
  coord_equal() +
  theme_jake_tile2()+
  theme(text=element_text(size=24, family='serif'), legend.title=element_blank(),strip.placement='outside', axis.text.y=element_blank(),legend.position='bottom')+
  facet_grid(cols = vars(Years))#+




# Output Figure 3
ggsave(filename = 'figures/Fig3.png', width = 11, height=11,units = 'in',
       plot = plot_grid(g,t,ncol=1,align='v'))




